import UserRolePermission from '@p/console/platform/UserRolePermission'
import MachineRoomGrant from '@p/console/platform/MachineRoomGrant'

export default {
  components: {
    UserRolePermission,
    MachineRoomGrant
  },
  props: {
    id: {
      type: Number,
      default: null
    },
    mobile: {
      type: String,
      default: null
    }
  },
  beforeMount() {
    if (this.mobile) {
      this.getUserByMobile()
    }
  },
  methods: {
    close() {
      this.$emit('update:show', false)
      this.$emit('update:id', null)
      this.$emit('update:mobile', null)
    },
    getUserByMobile() {
      this.submitting = true
      api.getUserByMobile({
        Mobile: this.mobile
      }).then(res => {
        let form = this.util.translateData(this.form, res.Data)

        form.Roles = form.Roles || []
        let roleIds = form.Roles.map(item => {
          return item.Id
        })
        form.Roles = roleIds

        form.Idcpoints = form.Idcpoints || []
        let machineRoomIds = form.Idcpoints.map(item => {
          return item.Id
        })
        form.Idcpoints = machineRoomIds

        form.Groups = form.Groups || []
        let groupIds = form.Groups.map(item => {
          return item.Id
        })
        form.Groups = groupIds

        this.form = form
        this.submitting = false
      }).catch(() => {
        this.submitting = false
      })
    },
    changeStep(value) {
      if (this.currentStep == 0) {
        this.$refs['form'].validate(valid => {
          if (valid) {
            this.currentStep += value
          }
        })
      } else {
        this.currentStep += value
      }
    },
    submit() {
      let form = this.objectUtil.copyObject(this.form)

      form.Roles = form.Roles.map(Id => {
        return {
          Id
        }
      })

      form.Idcpoints = (form.Idcpoints || []).map(Id => {
        return {
          Id
        }
      })

      form.Groups = (form.Groups || []).map(Id => {
        return {
          Id
        }
      })

      let fn
      if (this.id) {
        form.Id = this.id
        fn = this.handleUpdate
      } else {
        fn = this.handleAdd
      }

      this.submitting = true
      fn(form).then(res => {
        this.tipUtil.success('操作成功')
        this.$emit('ok')
        this.close()
      }).catch(() => {
        this.submitting = false
      })
    }
  }
}